<template>
  <div class="customer-dynamic">
    <Title v-if="showTitle" title="客户动态" />
    <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
    <Dynamic
      ref="Dynamic"
      style="height: 100%"
      :data="dynamicData"
      :moreShow="moreShow"
      @onLoadMore="loadMore"
      @onUpdateDy="searchFun"
      @onCallDetailShow="callDetailShow"
    ></Dynamic>
  </div>
</template>

<script lang="ts">
/**
 * 客户详情客户动态轨迹
 */
import { defineComponent, reactive, toRefs, computed, watch } from 'vue'
import Title from '@app/customer/components/title.vue'
import Dynamic from './dynamic-card.vue'
import { getDynamic } from '@app/customer/apis/pool'
import { getCallTimeLength } from '@/common/utils/common'
import { getCurrentDateTime, getFormatDateTime } from '@/common/utils/common'
import { commonStore } from '@/common/store/modules/common'
import searchForm from '@/common/components/base-form/form.vue'
const today = () => {
  const date = getCurrentDateTime().split(' ')[0]
  const lastDate = new Date(date + ' 00:00:00').getTime() - 7 * 24 * 60 * 60 * 1000
  const nextDate = new Date(date + ' 23:59:59').getTime()
  return [getFormatDateTime(new Date(lastDate), ''), getFormatDateTime(new Date(nextDate), '')]
}
export default defineComponent({
  name: 'CustomerDynamic',
  components: { Title, Dynamic, searchForm },
  props: {
    customerId: {
      type: String,
      default: ''
    },
    showTitle: {
      type: Boolean,
      default: true
    }
  },
  emits: ['onCallDetailShow'],
  setup(props, { emit }) {
    const state = reactive({
      dynamicData: [],
      form: {
        createTime: today(),
        category: []
      },
      pageData: {
        page: 1,
        limit: 10,
        total: 0
      },
      moreShow: false,
      fieldList: [
        {
          name: '类型',
          field: 'category',
          type: 'dropdown',
          multiple: true,
          choices: [
            {
              label: '通话记录',
              value: 'call'
            },
            {
              label: '跟进记录',
              value: 'follow'
            }
          ]
        },
        {
          name: '时间范围',
          field: 'createTime',
          type: 'datetime-range'
        }
      ]
    })

    const searchFun = async () => {
      state.dynamicData = []
      if (props.customerId) {
        state.pageData.page = 1
        console.log(state.dynamicData, 8822)
        getData()
      }
    }

    const globalFieldsObj: any = computed(() => {
      // 全局字段对象
      return commonStore().publicCache.globalFieldCacheObj || {}
    })

    const dyForm = computed(() => {
      // 动态表单
      return commonStore().publicCache.dyForm || []
    })

    const setData = () => {
      state.form.category = []
      state.form.createTime = today()
    }

    const getTitle = (type: any) => {
      switch (type) {
        case 'follow':
          return '跟进记录'
        case 'call':
          return '通话记录'
      }
    }

    const getFieldId = (field: string) => {
      // 获取全局字段备注idx
      let id = ''
      dyForm.value.forEach((item: any) => {
        if (item.scenes.includes('callCenter') && item.fields && item.fields.length) {
          item.fields.forEach((v: any) => {
            if (v.field === field && item.status) {
              // 备注字段且启用
              const obj = globalFieldsObj.value[v.field]
              id = obj && obj._id
            }
          })
        }
      })
      return id
    }

    const getAgentName = (id: string) => {
      const obj = commonStore().publicCache.userCacheObj[id] || {}
      if (obj.agentName) {
        return obj.agentName + '[' + obj.agentNumber + ']'
      }
      return '--'
    }

    const getData = () => {
      const { page, limit } = state.pageData
      const sendData = {
        customerId: props.customerId,
        page,
        limit,
        createTime: state.form.createTime,
        category: state.form.category
      }
      getDynamic(sendData).then((res) => {
        if (res.success && res.data) {
          if (res.data.list && res.data.list.length) {
            res.data.list.map((item: any) => {
              item.title = getTitle(item.category)
              item.agent = getAgentName(item.createAgent)
              if (item.content) {
                item.content.bridgeDuration = getCallTimeLength(item.content.bridgeDuration, false)
                item.content.agent = getAgentName(item.content.agentId)
              }
              if (item.serverNotes && item.serverNotes.length) {
                // 通话记录备注、服务标签-只展示返回的第一条服务小记里面的
                item.serverNotes[0].fields.forEach((v: any) => {
                  if (v._id === getFieldId('memo')) {
                    // 备注
                    item.memo = v.defaultValue
                  } else if (v._id === getFieldId('serviceLabel')) {
                    item.serviceLabels = v.defaultValue
                  }
                })
              }
            })
          }
          state.dynamicData = state.dynamicData.concat(res.data.list)
          console.log(state.dynamicData, res.data.list, 77)
          state.pageData.total = res.data.count
          if (state.pageData.total > limit * page) {
            state.moreShow = true
          } else {
            state.moreShow = false
          }
        }
      })
    }

    const loadMore = () => {
      const { total, page, limit } = state.pageData
      if (total > page * limit) {
        state.pageData.page++
        getData()
      }
    }

    const callDetailShow = (callId: string) => {
      emit('onCallDetailShow', callId)
    }

    watch(
      // 客户id变化
      () => props.customerId,
      () => {
        searchFun()
      },
      { immediate: true }
    )

    return {
      ...toRefs(state),
      loadMore,
      searchFun,
      setData,
      getData,
      callDetailShow
    }
  }
})
</script>

<style lang="stylus" scoped>
.customer-dynamic
  .el-form
    flex-wrap nowrap
</style>
